Deadlock in AWT if methods of the applet are over-synchronized


Symptoms

When running an applet in a browser using the Sun JavaTM Runtime Environment (JRETM), deadlock may occur if  methods of the applet are over-synchronized, especially those inherited from java.awt.Component. The same applet runs under the Microsoft Virtual Machine (VM).

Cause

The AWT class libraries are sometimes used by developers as thread-safe class libraries. Applets performed actions through the AWT using multiple threads, with the assumption that the class libraries would take care of synchronization issues.

However , the AWT class libraries guarantee thread safety only when calls are made from the AWT event dispatch thread. Because the implementation of the Microsoft VM and Sun differs, thread-unsafe code that runs without incident under one VM might fail under another.

One bad practice used by some applets is to synchronize every method of an applet to avoid possible race conditions or deadlocks in the Microsoft VM. However, this practice may result in deadlocks.

Resolution

To work around this problem, use synchronization in the applet only where it is really needed, and remove unnecessary synchronization. For example:

        public synchronized void paint(Graphics g) {
        ....
    }

    public synchronized void dispose() {       
        super.dispose();
        .....
    }

    public synchronized void stop() {
        ....
    }

    public synchronized void destroy() {
        ....
    }

In this case, the synchronized keyword in the paint, dispose, stop, and destroy methods should be removed because they are always called from a dedicated thread: paint and dispose by the AWT event dispatching thread; stop and destroy by the applet thread. The code should be changed as follows:

        public void paint(Graphics g) {
        ....
    }

    public void dispose() {       
        super.dispose();
        .....
    }

    public void stop() {
        ....
    }

    public void destroy() {
        ....
    }

Related Information

        The Java Tutorial discusses thread issues and techniques that apply both to AWT and Swing programs: How to Use Threads.